/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Controller;

import Model.AdminManager;
import Model.DateTime;
import Model.User;
import Model.UserManager;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author 013v
 */
public class LoginServlet extends HttpServlet {

    HashMap usermap = new HashMap();

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            boolean checker = false;

            User newUser = new User();
            DateTime datetime = new DateTime();

            DateFormat date = new SimpleDateFormat("yyyy/MM/dd");
            DateFormat time = new SimpleDateFormat("HH:mm:ss");
            Date date1 = new Date();
            Date time1 = new Date();

            newUser.setUsername(request.getParameter("username"));
            newUser.setPassword(request.getParameter("password"));
            String name = newUser.getUsername();

            checker = new UserManager().checkUser(newUser);

            if (usermap.containsKey(name) && usermap.get(name).equals(5)) {
                long timeC = new Date().getTime();
                long timeS = (Long) usermap.get(name.concat("time"));
                timeC = timeC - timeS;
                if (timeC < 1800000) {
                    response.sendRedirect("login.jsp?loginMax=true");
                } else {
                    usermap.remove(name);
                    response.sendRedirect("index.jsp");
                }
            } else if (usermap.containsKey(name)) {
                if (checker != true) {
                    int index = (Integer) usermap.get(name);
                    index = index + 1;
                    if (index < 5) {
                        usermap.put(name, index);
                    } else {
                        long timeS = new Date().getTime();
                        usermap.put(name, index);
                        usermap.put(name.concat("time"), timeS);
                    }
                    response.sendRedirect("login.jsp?loginAttempt=false");
                }
            } else if (checker != true) {
                usermap.put(name, 1);
                response.sendRedirect("login.jsp?loginAttempt=false");
            } else {
                HttpSession session = request.getSession();
                session.invalidate();
                session = request.getSession(true);
                User tempUser = new UserManager().getIDType(newUser);
                session.setAttribute("username", newUser.getUsername());
                session.setAttribute("uid", tempUser.getAccountID());
                session.setAttribute("acctype", tempUser.getUserType());
                session.setAttribute("status", tempUser.getStatus());
                usermap.remove(name);

                if (tempUser.getStatus() != 0) {
                    datetime.setAccountID(tempUser.getAccountID());
                    datetime.setDate(date.format(date1));
                    datetime.setTime(time.format(time1));
                    boolean result = new UserManager().timeLog(datetime);
                    if (result == true) {
                        if (tempUser.getUserType() != 5 && tempUser.getUserType() != 6) {
                            long timerRJ = new Date().getTime();
                            boolean timeRes = new AdminManager().checkManagerLogin24(tempUser, timerRJ);
                            if (timeRes || tempUser.getStatus() == 1) {
                                if (tempUser.getStatus() == 1) {
                                    usermap.remove(tempUser.getAccountID());
                                    if (tempUser.getUserType() != 7) {
                                        response.sendRedirect("prman/prodHome.jsp");
                                    } else {
                                        response.sendRedirect("acman/accountingManager.jsp");
                                    }
                                } else {
                                    usermap.put(tempUser.getAccountID(), 1);
                                    if (tempUser.getUserType() != 7) {
                                        response.sendRedirect("prman/prodHome.jsp");
                                    } else {
                                        response.sendRedirect("acman/accountingManager.jsp");
                                    }
                                }
                            } else if (usermap.containsKey(tempUser.getAccountID()) && usermap.get(tempUser.getAccountID()).equals(1)) {
                                //do checking for changed
                                if (tempUser.getStatus() == 1) {
                                    if (tempUser.getUserType() != 7) {
                                        response.sendRedirect("prman/prodHome.jsp");
                                    } else {
                                        response.sendRedirect("acman/accountingManager.jsp");
                                    }
                                } else {
                                    response.sendRedirect("managerpages/changeMPassword.jsp?attempt=false");
                                }
                            } else {
                                response.sendRedirect("LogoutServlet");
                            }
                        } else if (tempUser.getUserType() == 5) {
                            response.sendRedirect("admin/verwalter.jsp");
                        } else if (tempUser.getUserType() == 6) {
                            String[][] userCart = new String[3][10];
                            session.setAttribute("cartArray", userCart);
                            session.setAttribute("numCart", 0);
                            session.setAttribute("checkflag", 0);
                            response.sendRedirect("index.jsp");
                        }
                    } else {
                        response.sendRedirect("login.jsp?loginAttempt=false");
                    }
                }
            }
        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
